<?php

namespace Mobile\Controller;

use Think\Controller;

/**
 * Description of PublicController.class控制器实例
 * 
 * @author songanwei
 * @date 2016-1-22
 */
class PublicController extends \Common\Controller\BaseController {

    protected function _initialize() {
        parent::_initialize();
        $this->validateUtil = new \Org\Util\Validate();
    }

    /**
     * @description 移动端客栈申请
     * @modify songanwei 2016-01-22
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function apply() {
        $params = I('post.');
        $hotelName = I('post.hotel');
        $cityName = I('post.address');
        $mobile = I('post.mobile');
        $userName = I('post.name');

        // v2.0.11的参数校验 支持国际号码校验 tb_universal_time
        $version = getVersion(array('2.0.19', '2.0.16', '2.0.11'));
        if ($version >= '2.0.11') {
            $areaCode = I('post.areaCode', '86', 'string');
            $universalTimeId = I('post.universalTimeId', '5', 'string');
            $this->ajaxValidateReturn($this->validateUtil, $mobile, 'globalMobile',
                        array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                    ));
            $universalTimeModel = D('UniversalTime');
            $universalTimeInfo = $universalTimeModel->getInfo($universalTimeId);
            $countryId = $universalTimeInfo['country_id'];
        } else {
            $this->ajaxValidateReturn($this->validateUtil, $mobile, 'notnull,notempty,mobile');
        }

        if ($version >= '2.0.16') {
            $verify = $params['verify'];
            $redis = new \Org\Util\RedisHelper();
            $result = $redis->verify($areaCode . $mobile, $verify);
            if ($result === false) {
                returnJson(403, 202);
            }
            $cityId = isset($params['cityId']) ? $params['cityId'] : null;
            $districtId = isset($params['districtId']) ? $params['districtId'] : null;
            //验证参数
            $this->ajaxValidateReturn($this->validateUtil, $cityId, 'notnull,notempty,id');
            $this->ajaxValidateReturn($this->validateUtil, $districtId, 'notnull,notempty,id');
        }

        $currencyId = isset($params['currencyId']) ? $params['currencyId'] : null;
        if ($version >= '2.0.19') {
            $this->ajaxValidateReturn($this->validateUtil, $currencyId, 'notnull,notempty,id');
        }

        //验证参数
        $this->ajaxValidateReturn($this->validateUtil, $hotelName, 'notnull,notempty,nameLength20');
        $this->ajaxValidateReturn($this->validateUtil, $cityName, 'notnull,notempty,nameLength20');
        $this->ajaxValidateReturn($this->validateUtil, $userName, 'notnull,notempty,nameLength20');
        //检查参数
        $hotelApplyLogic = A('Common/HotelApply', 'Logic');

        if ($version >= '2.0.19') {
            // v2.0.19 增加多货币
            $hotelApplyLogic->addApplyHotel($hotelName, $cityName, $mobile, $userName, $universalTimeId, $areaCode, $countryId, $cityId, $districtId, $currencyId);
        } else if ($version >= '2.0.16') {
            $hotelApplyLogic->addApplyHotel($hotelName, $cityName, $mobile, $userName, $universalTimeId, $areaCode, $countryId, $cityId, $districtId);
        } else if ($version >= '2.0.11') {
            // v2.0.11增加参数 $universalTimeId, $areaCode
            $hotelApplyLogic->apply($hotelName, $cityName, $mobile, $userName, 0, '', $universalTimeId, $areaCode, $countryId);
        } else {
            $hotelApplyLogic->apply($hotelName, $cityName, $mobile, $userName, 0, '');
        }

        returnJson(200, 200, 'success');
    }

    /**
     * @description 发送短信验证码
     * @modify songanwei 2016-01-22
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function sendVcode() {
        $params = I('param.');
        $mobile = $params['mobile'];

        // v2.0.11的参数校验 支持国际号码校验
        $version = getVersion(array('2.0.11'));
        if ($version >= '2.0.11') {
            $areaCode = I('post.areaCode', '86', 'string');
            $this->ajaxValidateReturn($this->validateUtil, $mobile, 'globalMobile',
                        array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                    ));
        }

        //检查用户是否存在
        $adminLoginModel = D('AdminLogin');
        $areaCode = isset($areaCode) ? $areaCode : '86';
        $adminLogin = $adminLoginModel->getInfoByMobile($mobile, $areaCode);
        if (!$adminLogin) {
            returnJson(403, 100);
        }

        session_id($mobile);
        session_start();
        $sendTime = session(C('RESET_PASSWORD_VCODE_SEND_TIME'));
        //发送短信一分钟一次
        if (!empty($sendTime) && !isOverMinute($sendTime, 1)) {
            returnJson(403, 107, 'error');
        }
        $token = getRandomNumber();
        //发送短信
        if ($version >= '2.0.11' && isset($areaCode)) {
            if ($areaCode == '86') {
                $smsSender = new \Org\Util\Sms();
                $result = $smsSender->sendVocode($mobile, $token);
            } else {
                $yunPian = new \Org\Util\yunPian();
                $result = $yunPian->sendVcode($areaCode, $mobile, $token);
            }
        } else {
            $smsSender = new \Org\Util\Sms();
            $result = $smsSender->sendVocode($mobile, $token);
        }

        if (!$result) {
            returnJson(403, 151, 'error');
        }
        $now = time();
        session(C('RESET_PASSWORD_VCODE_SEND_TIME'), $now);
        session(C('RESET_PASSWORD_VCODE'), $token);
        session(C('RESET_PASSWORD_MOBILE'), $mobile);
        returnJson(200, 200);
    }

    /**
     * @description  重置密码
     * @modify songanwei 2016-01-22
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function resetPassword() {
        $params = I('post.');

        // v2.0.11的参数校验 支持国际号码校验
        $version = getVersion(array('2.0.11'));
        if ($version >= '2.0.11') {
             $validateRule = array(
                'mobile' => 'notnull,notempty',
                'vcode' => 'notnull,notempty,vcode6',
                'password' => 'notnull,notempty'
            );
            $areaCode = I('post.areaCode', '86', 'string');
            $this->ajaxValidateReturn($this->validateUtil, $params['mobile'], 'globalMobile',
                        array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                    ));
        } else {
             $validateRule = array(
                'mobile' => 'notnull,notempty,mobile',
                'vcode' => 'notnull,notempty,vcode6',
                'password' => 'notnull,notempty'
            );
        }

        $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);

        $mobile = $params['mobile'];
        $vcode = $params['vcode'];
        $encryptPassword = $params['password'];

        $adminLoginModel = D('AdminLogin');
        $areaCode = isset($areaCode) ? $areaCode : '86';
        $adminLogin = $adminLoginModel->getInfoByMobile($mobile, $areaCode);
        if (!$adminLogin) {
            returnJson(403, 100);
        }

        session_id($mobile);
        session_start();

        $sessionMobile = session(C('RESET_PASSWORD_MOBILE'));
        $sessionVcode = session(C('RESET_PASSWORD_VCODE'));
        $sessionTime = session(C('RESET_PASSWORD_VCODE_SEND_TIME'));

        //验证短信验证码
        if (($sessionMobile != $mobile) || ($vcode != $sessionVcode) || (($sessionTime + 300) < time())) {
            returnJson(403, 120);
        }

        //解析密码
        $rsaObject = new \Org\Util\RSAEncrypt();
        $decryptPassword = $rsaObject->meizhuDecrypt($encryptPassword);
        //获取用户真实密码
        $password = substr($decryptPassword, 8);
        //更新密码
        $result = $adminLoginModel->setPassword($adminLogin['id'], hash("sha256", $password));
        //返回结果
        if ($result == false) {
            returnJson(500, 509, 'error');
        }
        returnJson(200, 200, 'success');
    }

    /**
     * 获取区号数据
     * @modify Paddy 2017-03-22
     */
    public function getAreaCode() {
        //获取区号数据
        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('MANAGE_PUBLIC_URL'));
        $client->setEncryptMode(3);
        $RPCData = array(
            'flag' => 'uclbrt',
            'time' => time(),
        );

        $result = $client->getAreaCode($RPCData);
        if (!is_array($result)) {
            returnJson(500, 512, 'error');
        }
        returnJson(200, 200, $result);
    }

    /**
     * 申请账号页面 获取省份
     * @modify wenhui 2017-09-15
     */
    public function getProvinceList() {
        $param = I('post.');
        $validator = new \Org\Util\Validate();

        $universalTimeId = $param['universalTimeId'];
        $idValidatePass = $validator->validate($universalTimeId, 'notempty,notnull,id');

        //获取城市
        $HotelLogic = A('Common/Hotel', 'Logic');
        $provinceData = $HotelLogic->getProvinceList($universalTimeId);

        returnJson(200, 200, $provinceData);
    }

    /**
     * 申请账号页面 获取城市
     * @modify wenhui 2017-09-15
     */
    public function getCityList() {
        $param = I('post.');
        $validator = new \Org\Util\Validate();

        $provinceId = $param['provinceId'];
        $idValidatePass = $validator->validate($provinceId, 'notempty,notnull,id');

        //获取城市
        $HotelLogic = A('Common/Hotel', 'Logic');
        $cityListData = $HotelLogic->getCityList($provinceId);

        returnJson(200, 200, $cityListData);
    }

     /**
     * 申请账号页面 获区域
     * @modify wenhui 2017-09-15
     */
    public function getDistrictList() {
        $param = I('post.');
        $validator = new \Org\Util\Validate();

        $cityId = $param['cityId'];
        $idValidatePass = $validator->validate($cityId, 'notempty,notnull,id');

        //获取城市
        $HotelLogic = A('Common/Hotel', 'Logic');
        $districtData = $HotelLogic->getDistrictList($cityId);

        returnJson(200, 200, $districtData);
    }
    /**
     * 获取验证码
     * @modify zane 2017-09-20
     */
    public function getVerify() {
        $param = I('request.');
        $mobile = $param['mobile'];
        $areaCode = $param['areaCode'];
        $ip = sprintf('%u',ip2long(get_client_ip()));
        $ipKey = 'ip:'.$ip;
        $redis = new \Redis();
        $connectResult = $redis->connect(C('REDIS_SERVERIP'), C('REDIS_SERVERPORT'));
        $redisAuthResult = $redis->auth(C('REDIS_AUTH_PASSWORD'));
        if ($connectResult && $redisAuthResult) {
        } else {
            returnJson(403, 202);
        }
        $times = $redis->get($ipKey);
        if ($times >= 50) {
            returnJson(500, 513);
        } elseif ($times === false) {
            $redis->set($ipKey, 1, 86400);
        } else {
            $ttl = $redis->ttl($ipKey);
            $redis->set($ipKey, ++$times, $ttl);
        }
        $token = time() . rand(0,9999);
        $token = longto62($token);

        $result = $redis->set($areaCode . $mobile, $token, 300);

        if ($result === true) {
            $rsa = new \Org\Util\RSAEncrypt();
            $txt = $rsa->verifyEncrypt($token);
            returnJson(200, 200, $txt);
        } else {
            returnJson(403, 202);
        }
    }

    /**
     * 获取系统货币
     * @modify wenhui 2018-02-06
     */
    public function getBpCurrency() {
        $currencyLogic = A('Common/Currency', 'Logic');
        $currencyData = $currencyLogic->getBpCurrency();

        returnJson(200, 200, $currencyData);
    }
}
